package com.qdxwx.web.controller.order;

import com.alibaba.fastjson2.JSONObject;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.enums.PayType;
import com.qdxwx.payment.wxpay.WxPay;
import com.qdxwx.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/order")
public class WxPayController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(WxPayController.class);
	@Autowired
	private OrderService orderService;
	@Autowired
	private WebsiteProfileService websiteProfileService;

	/**
	 * 课程订单微信支付通知
	 */
	@RequestMapping(value = "/wxpay/notify")
	@ResponseBody
	public JSONObject wxpayReturn(HttpServletRequest request) {
		//判断签名是否正确(这里还需加强判断)
		JSONObject resourceMap = WxPay.getNotifyResource(request);
		if (resourceMap == null) {
			return WxPay.getNotifyReply("获取通知资源错误！");
		}
		Map<String, Object> payConfig = websiteProfileService.getWxpay();// 获得微信支付配置
		// 微信支付的API密钥
		String apiKey = (String) payConfig.get("apiKey"); // key
		JSONObject cipherMap = WxPay.getResourceDecrypt(resourceMap, apiKey);
		if (cipherMap == null) {
			return WxPay.getNotifyReply("获取通知资源解码错误！");
		}
		//执行自己的业务逻辑开始
		String appId = cipherMap.getString("appid");
		String mchId = cipherMap.getString("mchid");
		//本地订单号orderNo/payNo
		//支付平台的out_trade_no为本地的orderNo(不要搞混了)
		String orderNo = cipherMap.getString("out_trade_no");
		//微信支付系统生成的订单号
		//支付平台的transaction_id为本地的outTradeNo(不要搞混了)
		String transactionId = cipherMap.getString("transaction_id");
		//交易类型，枚举值：
		//JSAPI：公众号支付
		//NATIVE：扫码支付
		//APP：APP支付
		//MICROPAY：付款码支付
		//MWEB：H5支付
		//FACEPAY：刷脸支付
		String tradeType = cipherMap.getString("trade_type");
		//交易状态，枚举值：
		//SUCCESS：支付成功
		//REFUND：转入退款
		//NOTPAY：未支付
		//CLOSED：已关闭
		//REVOKED：已撤销（付款码支付）
		//USERPAYING：用户支付中（付款码支付）
		//PAYERROR：支付失败(其他原因，如银行返回失败)
		String tradeState = cipherMap.getString("trade_state");
		//交易状态描述 示例值：支付成功
		String tradeStateDesc = cipherMap.getString("trade_state_desc");
		//银行类型，采用字符串类型的银行标识
		String bankType = cipherMap.getString("bank_type");
		//附加数据，原样返回的
		String attach = cipherMap.getString("attach");
		//支付完成时间
		//String successTimeStr = cipherMap.getString("success_time");
		//LocalDateTime successTime = TKConvert.toLocalDateTime(successTimeStr.substring(0, 19));
		//支付者的唯一标识
		//String openid = cipherMap.getJSONObject("payer").getString("openid");
		//支付金额信息（暂没什么用）
		JSONObject amountMap = cipherMap.getJSONObject("amount");
		int total = amountMap.getIntValue("total");//订单金额
		int payerTotal = amountMap.getIntValue("payer_total");//支付金额
		//if (payerTotal < total){
			//这里可做订单部分支付操作
		//}
		//处理业务开始
		if ("SUCCESS".equals(tradeState)) {
			//这里是支付成功，处理订单
			//String openid = cipherMap.getString("payer.openid");
			// 必须校验支付的金额
			Map<String, Object> sourceMap = new HashMap<>();
			sourceMap.put("orderNo", orderNo);
			sourceMap.put("total_fee", payerTotal);
			sourceMap.put("outTradeNo", transactionId);
			sourceMap.put("payType", PayType.WXPAY.toString());

			AjaxResult res = orderService.updateCompleteOrder(request, sourceMap);

			//通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
			if (res.getCode() == 0) {
				return WxPay.getNotifyReply("SUCCESS");
			} else {
				return WxPay.getNotifyReply(res.getMsg());
			}
		} else {
			logger.error("支付失败,错误信息：" + tradeStateDesc);
			return WxPay.getNotifyReply("支付失败,错误信息：" + tradeStateDesc);
		}
	}

	/*
	@RequestMapping(value = "/wxpay/notify/test")
	@ResponseBody
	public JSONObject wxpayReturnTest(HttpServletRequest request) {
		//判断签名是否正确(这里还需加强判断)
			//这里是支付成功，处理订单
			//String openid = cipherMap.getString("payer.openid");
			// 必须校验支付的金额
			Map<String, Object> sourceMap = new HashMap<>();
			sourceMap.put("orderNo", "1P20220425230554507");
			sourceMap.put("total_fee", 9900);
			sourceMap.put("outTradeNo", "transactionId");
			sourceMap.put("payType", PayType.WXPAY.toString());

			AjaxResult res = orderService.updateCompleteOrder(request, sourceMap);

			//通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
			if (res.getCode() == 0) {
				return WxPay.getNotifyReply("SUCCESS");
			} else {
				return WxPay.getNotifyReply(res.getMsg());
			}
	}*/
}